package org.jpro.datasource;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.jpro.enums.DataSourceType;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * <P>功能描述 : 动态数据源 </P>
 * <P>File name : DynamicDataSource </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/3/1 下午6:00</P>
 */
@Slf4j
@Getter
@Setter
@Primary
@Configuration("dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public class DynamicDataSource extends AbstractRoutingDataSource {

    private Read read = new Read();

    private Write write = new Write();

    /**
     * <P>功能描述 : 初始化读写数据源 </P>
     * <P>Method Name : init </P>
     * <P>Author : 王泽浩 </P>
     * <P>E-Mail : 1028625100@qq.com </P>
     * <P>Date : 2017-03-01 22:45:35</P>
     * @since 1.0
     */
    @PostConstruct
    public void init() {
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        targetDataSources.put(DataSourceType.READ, read.dataSource());
        targetDataSources.put(DataSourceType.WRITE, write.dataSource());
        super.setTargetDataSources(targetDataSources);
        super.setDefaultTargetDataSource(write.dataSource());
        log.debug("设置读写数据源，默认数据源为写数据源");
    }

    /**
     * <P>功能描述 : 切换数据源方法</P>
     * <P>Method Name : determineCurrentLookupKey </P>
     * <P>Author : 王泽浩 </P>
     * <P>E-Mail : 1028625100@qq.com </P>
     * <P>Date : 2017-03-01 22:45:56</P>
     * @return the object
     * @since 1.0
     */
    @Override
    protected Object determineCurrentLookupKey() {
        DataSourceType dataSourceType = DataSourceContextHolder.getDataSourceType();
        if (dataSourceType == null) {
            log.debug("使用写数据源操作数据库");
            return null;
        } else {
            DataSourceContextHolder.clearDataSourceType();
            log.debug("使用{}数据源操作数据库", dataSourceType);
            return dataSourceType.name();
        }
    }

    /**
     * <P>功能描述 : 读数据源</P>
     * <P>Method Name : Read </P>
     * <P>Author : 王泽浩 </P>
     * <P>E-Mail : 1028625100@qq.com </P>
     * <P>Date : 2017-03-01 22:44:33</P>
     * @since 1.0
     */
    public class Read extends AbstractDatasource {
    }

    /**
     * <P>功能描述 : 写数据源</P>
     * <P>Method Name : Write </P>
     * <P>Author : 王泽浩 </P>
     * <P>E-Mail : 1028625100@qq.com </P>
     * <P>Date : 2017-03-01 22:44:39</P>
     * @since 1.0
     */
    public class Write extends AbstractDatasource {
    }

}
